#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2019-12-07
"""

import logging
from uuid import uuid4
import xmlrpclib

from apscheduler.jobstores.base import JobLookupError
from mmonitor.common.config import rpc_port, rpc_host

from mmonitor.main.spider import SpiderBase


def apscheduler_trigger_args(**kwargs):
    """Figure out the avaliable date parameters based on specific trigger.
    And add job to apscheduler.
    """
    job_type = kwargs['job_type']

    date_fields = []
    if job_type == 'date':
        date_fields = ['timezone', 'run_date']
    elif job_type == 'interval':
        date_fields = ['weeks', 'days', 'hours', 'minutes', 'seconds',
                       'start_date', 'end_date', 'timezone']
    elif job_type == 'cron':
        date_fields = [
            'year', 'month', 'week', 'day_of_week', 'hour',
            'minute', 'timezone', 'start_date', 'end_date'
        ]

    date_fields_map = {}
    for item in date_fields:
        value = kwargs.get(item, None)
        if value is not None:
            if item in ['weeks', 'days', 'hours', 'minutes', 'seconds']:
                date_fields_map[item] = int(value)
            else:
                date_fields_map[item] = str(value)
    print date_fields_map

    return date_fields_map


class Apscheduler(object):

    def __init__(self):
        self.rpc = xmlrpclib.ServerProxy('http://{}:{}'.format(rpc_host, rpc_port), allow_none=True)

    def add_job(self, url, url_id):

        args = dict(url_id=url_id, url=url)
        trigger_args = {}
        trigger_args["kwargs"] = args
        trigger_args['seconds'] = 5
        trigger_args.update({"job_type": "interval"})
        try:
            Job = self.rpc.add_job('mmonitor.main.spider.run_job', trigger_args)
            return Job
        except xmlrpclib.Error as e:
            logging.error('call scheduler rpc error %s' % e)
            raise

    def delete_job(self, job_id):
        try:
            self.rpc.remove_job(job_id)
        except xmlrpclib.Error as e:
            if 'JobLookupError' in str(e):
                raise JobLookupError(job_id)
            raise
        return {'job_id': job_id}

    def modify_job(self, **kwargs):
        """Reschedule the job.
        """
        job_id = kwargs['job_id']
        job_type = kwargs['job_type']

        trigger_args = apscheduler_trigger_args(**kwargs)
        if len(trigger_args) == 0: return
        trigger_args['trigger'] = job_type
        try:
            self.rpc.reschedule_job(job_id, trigger_args)
        except xmlrpclib.Error as e:
            if 'JobLookupError' in str(e):
                raise JobLookupError(job_id)
            raise
        return {'job_id': job_id}

    def pause_job(self, job_id):
        """Causes the given job not to be executed until it is explicitly
        resumed.
        :param str|unicode job_id: the identifier of the job
        """
        try:
            self.rpc.pause_job(job_id)
        except xmlrpclib.Error as e:
            if 'JobLookupError' in str(e):
                raise JobLookupError(job_id)
            raise
        return {'job_id': job_id}

    def resume_job(self, job_id):
        """Resumes the schedule of the given job, or removes the job if
        its schedule is finished.
        :param str|unicode job_id: the identifier of the job
        """
        try:
            self.rpc.resume_job(job_id)
        except xmlrpclib.Error as e:
            if 'JobLookupError' in str(e):
                raise JobLookupError(job_id)

            raise
        return {'job_id': job_id}

if __name__ == "__main__":
    scheduler = Apscheduler()
    param_remove = {'url':"www.sina.com.cn", "url_id":"aaa"}
    print(scheduler.add_job(**param_remove))
    # print(scheduler.delete_job("48fa95cf96594f0ebe63fb25fc4dd180"))